package com.neusoft.comtroller;

import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

public class jedisTest {

    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.1.7", 6379);

        System.out.println(jedis.ping() + "测试是否连接成功，反PONG 则为成功");
        System.out.println(jedis.flushDB() + "清空当前数据库");
        System.out.println(jedis.flushAll() + "清空所有数据库");
        System.out.println(jedis.exists("key") + "查询是否存在键");
        System.out.println(jedis.set("username", "root") + "新增username的键 root 的值");
        System.out.println(jedis.type("username") + "查询username键对应值得类型什么");
        System.out.println(jedis.rename("username", "name") + "键的重命名 username 改为name");
        System.out.println(jedis.randomKey() + "随件反馈一个键空间的中一个");
        System.out.println(jedis.keys("*") + "查询所有的Key");
        System.out.println(jedis.del("name") + "删除name键");
        System.out.println(jedis.select(0) + "按照索引查询");
        System.out.println(jedis.dbSize() + "当前数据库的数目");
        System.out.println("《================={===");
        System.out.println(jedis.lpush("key1", "val1", "key2", "val2") + "添加一个 List集合");
        System.out.println(jedis.lrange("key1", 0, -1) + "-1代表查询全部");
        System.out.println("--------------------------------下面是redis开启事务测试----------------------------------------------------------------------");

        // json 字符串

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("hello", "word");
        jsonObject.put("name", "mr_wang");

        // 开始事务
        Transaction multi = jedis.multi();
        try {
            multi.set("name", jsonObject.toJSONString());
            // 如果执行代码报错，事务启动
            //int i = 1/0;

            // 提交事务
            multi.exec();
        } catch (Exception e) {
            // 放弃事务
            multi.discard();
            e.printStackTrace();
        } finally {

            System.out.println(jedis.get("name"));
            // 关闭连接
            jedis.close();
        }

    }
}
